package com.easylinkin.linkappapi.penetsecuremanage.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.penetsecuremanage.dto.RailLinkappGridManagementInfoDTO;
import com.easylinkin.linkappapi.penetsecuremanage.entity.RailLinkappGridManagementInfo;
import com.easylinkin.linkappapi.penetsecuremanage.mapper.RailLinkappGridManagementInfoMapper;
import com.easylinkin.linkappapi.penetsecuremanage.mapper.RailLinkappOrgInfoMapper;
import com.easylinkin.linkappapi.penetsecuremanage.service.IRailLinkappGridManagementInfoService;
import com.easylinkin.linkappapi.penetsecuremanage.vo.*;
import com.easylinkin.linkappapi.roster.entity.RailLinkappRosterPersonnel;
import com.easylinkin.linkappapi.roster.mapper.RailLinkappRosterPersonnelMapper;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.mapper.LinkappTenantMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.misc.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author lyk
 * @date 2025/6/20 下午 2:26
 */
@Service
@Slf4j
public class RailLinkappGridManagementInfoServiceImpl extends ServiceImpl<RailLinkappGridManagementInfoMapper, RailLinkappGridManagementInfo> implements IRailLinkappGridManagementInfoService {
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private RailLinkappRosterPersonnelMapper rosterPersonnelMapper;
    @Resource
    private CommonService commonService;
    @Autowired
    private LinkappTenantMapper tenantMapper;

    @Autowired
    private RailLinkappRosterPersonnelMapper railLinkappRosterPersonnelMapper;

    @Autowired
    private SysDictItemService dictItemService;

    @Autowired
    private RailLinkappOrgInfoMapper railLinkappOrgInfoMapper;

    @Override
    public IPage<RailLinkappGridManagementInfoVO> selectPage(Page page, RailLinkappGridManagementInfoDTO customQueryParams) {
        customQueryParams.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page,customQueryParams);
    }

    @Override
    public List<RailLinkappGridManagementInfoVO> getList(RailLinkappGridManagementInfoDTO dto) {
        dto.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.getList(dto);
    }

    @Override
    public List<String> saveList(RailLinkappGridManagementInfoDTO dto) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //记录安监专务id
        List<String> ajzwIds = new ArrayList<>();
        //记录其他人员id
        List<String> outhIds = new ArrayList<>();
        List<String> errs = new ArrayList<>();
        Map<String, String> name_map = new HashMap<>();
        //保存前置校验
        List<RailLinkappGridManagementInfoDTO> adds = dto.getAddList();
        for (int i=0;i<adds.size();i++){
            RailLinkappGridManagementInfoDTO railLinkappGridManagementInfoDTO = adds.get(i);
            if (StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getGridName())){
                errs.add("第"+(i+1)+"行记录，网格名称不能为空");
            }
            Integer integer = baseMapper.countByGridName(tenantId, railLinkappGridManagementInfoDTO.getGridName());
            if (integer>0){
                errs.add("第"+(i+1)+"行记录，网格名称不能重复");
            }
            String s = name_map.get(railLinkappGridManagementInfoDTO.getGridName());
            if (!StringUtils.isEmpty(s)){
                errs.add("第"+(i+1)+"行记录，新增的网格信息内和其他网格名称不能重复");
            }
            name_map.put(railLinkappGridManagementInfoDTO.getGridName(),railLinkappGridManagementInfoDTO.getGridName());
            if (!StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getSafetySupId())){
                boolean contains = outhIds.contains(railLinkappGridManagementInfoDTO.getSafetySupId());
                if (contains){
                    errs.add("第"+(i+1)+"行记录，"+"安监专务"+"已经担任了其他职务，不能担任安监专务");
                }
                //判断网格安全员在历史网格中是否有担任职位
                Integer checkAjNumber = baseMapper.checkAjzwByNumber(tenantId,railLinkappGridManagementInfoDTO.getSafetySupId());
                if (!Objects.isNull(checkAjNumber)){
                    if (checkAjNumber>0){
                        errs.add("第"+(i+1)+"行记录，"+"安监专务"+"已经担任了其他网格的其他职务，不能担任安监专务");
                    }
                }
                ajzwIds.add(railLinkappGridManagementInfoDTO.getSafetySupId());
            }

            //网格安全员判断
            if (!StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getGridSecId())){
                boolean contains = ajzwIds.contains(railLinkappGridManagementInfoDTO.getGridSecId());
                if (contains){
                    errs.add("第"+(i+1)+"行记录，"+"网格安全员"+"已经担任了安监专务，不能担任其他职务");
                }
                //安监专务校验
                Integer checkOtherSum = baseMapper.checkOtherByNumber(tenantId,railLinkappGridManagementInfoDTO.getGridSecId());
                if (!Objects.isNull(checkOtherSum)){
                    if (checkOtherSum>0) {
                        errs.add("第" + (i + 1) + "行记录，" +"网格安全员"+ "已经担任了其他网格的安监专务，不能担任其他职务");
                    }
                }
                //其他确实校验 （表内）
                /*if(outhIds.contains(railLinkappGridManagementInfoDTO.getGridSecId())){
                    errs.add("第" + (i + 1) + "行记录，" + railLinkappGridManagementInfoDTO.getGridSecName() + "已经担任了当前表格内的其他职位，不能重复");
                }*/
             /*  Integer checkAjNumber = baseMapper.checkAjzwByNumber(tenantId,railLinkappGridManagementInfoDTO.getGridSecId());
                if(!Objects.isNull(checkAjNumber)){
                    if (checkAjNumber>0) {
                        errs.add("第" + (i + 1) + "行记录，" + railLinkappGridManagementInfoDTO.getGridSecName() + "已经担任了其他网格内的其他职位，不能重复");
                    }
                }*/
                outhIds.add(railLinkappGridManagementInfoDTO.getGridSecId());
            }else{
                errs.add("第"+(i+1)+"行记录，网格安全员不能为空");
            }
            //施工员/领工员
            if (!StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getGridForemanId())){
                boolean contains = ajzwIds.contains(railLinkappGridManagementInfoDTO.getGridForemanId());
                if (contains){
                    errs.add("第"+(i+1)+"行记录，"+"施工员/领工员"+"已经担任了安监专务，不能担任其他职务");
                }
                //安监专务校验
                Integer checkOtherSum = baseMapper.checkOtherByNumber(tenantId, railLinkappGridManagementInfoDTO.getGridForemanId());
                if (!Objects.isNull(checkOtherSum)){
                    if (checkOtherSum>0) {
                        errs.add("第" + (i + 1) + "行记录，"+"施工员/领工员"+"已经担任了其他网格的安监专务，不能担任其他职务");
                    }
                }
                //其他确实校验 （表内）
              /*  if(outhIds.contains(railLinkappGridManagementInfoDTO.getGridForemanId())){
                    errs.add("第" + (i + 1) + "行记录，" + railLinkappGridManagementInfoDTO.getGridSecName() + "已经担任了当前表格内的其他职位，不能重复");
                }
                Integer checkAjNumber = baseMapper.checkAjzwByNumber(tenantId,railLinkappGridManagementInfoDTO.getGridForemanId());
                if(!Objects.isNull(checkAjNumber)){
                    if (checkAjNumber>0) {
                        errs.add("第" + (i + 1) + "行记录，" + railLinkappGridManagementInfoDTO.getGridSecName() + "已经担任了其他网格内的其他职位，不能重复");
                    }
                }*/
                outhIds.add(railLinkappGridManagementInfoDTO.getGridForemanId());
            }
            //现场负责人/安全员
            if (!StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getGridSitemanId())){
                boolean contains = ajzwIds.contains(railLinkappGridManagementInfoDTO.getGridSitemanId());
                if (contains){
                    errs.add("第"+(i+1)+"行记录，"+"现场负责人/安全员"+"已经担任了安监专务，不能担任其他职务");
                }
                //安监专务校验
                Integer checkOtherSum = baseMapper.checkOtherByNumber(tenantId,railLinkappGridManagementInfoDTO.getGridSitemanId());
                if (!Objects.isNull(checkOtherSum)){
                    if (checkOtherSum>0) {
                        errs.add("第" + (i + 1) + "行记录，" + "现场负责人/安全员" + "已经担任了其他网格的安监专务，不能担任其他职务");
                    }
                }
                //其他确实校验 （表内）
               /* if(outhIds.contains(railLinkappGridManagementInfoDTO.getGridSitemanId())){
                    errs.add("第" + (i + 1) + "行记录，" + railLinkappGridManagementInfoDTO.getGridSecName() + "已经担任了当前表格内的其他职位，不能重复");
                }
                Integer checkAjNumber = baseMapper.checkAjzwByNumber(tenantId,railLinkappGridManagementInfoDTO.getGridSitemanId());
                if(!Objects.isNull(checkAjNumber)){
                    if (checkAjNumber>0) {
                        errs.add("第" + (i + 1) + "行记录，" + railLinkappGridManagementInfoDTO.getGridSecName() + "已经担任了其他网格内的其他职位，不能重复");
                    }
                }*/
                outhIds.add(railLinkappGridManagementInfoDTO.getGridSitemanId());
            }
            //网格安全员是否正式职工
            if (StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getIsFormalEmployee())){
                errs.add("第"+(i+1)+"行记录，网格安全员是否正式职工不能为空");
            }
            //网格安全员是否是专职
            if (StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getIsSoleDuty())){
                errs.add("第"+(i+1)+"行记录，网格安全员是否专职不能为空");
            }
            //安全员证书
            if (StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getHoldCert())){
                errs.add("第"+(i+1)+"行记录，网格安全员证书不能为空");
            }
            //备注
            if (!StringUtils.isEmpty(railLinkappGridManagementInfoDTO.getNotes())){
                if(railLinkappGridManagementInfoDTO.getNotes().length()>50){
                    errs.add("第"+(i+1)+"行记录，备注不能超过50字");
                }
            }
        }
        if (errs.size()>0){
            return errs;
        }
        Integer number_d = baseMapper.countIndexMaxNumber(tenantId);
        if (Objects.isNull(number_d)){
            number_d = 1;
        }
        if (number_d == 0){
            number_d = 1;
        }
        for (RailLinkappGridManagementInfoDTO addDto:adds){
            //姓名同步
            //安监
            if (!StringUtils.isEmpty(addDto.getSafetySupId())){
                RailLinkappRosterPersonnel personnel = rosterPersonnelMapper.selectById(Long.valueOf(addDto.getSafetySupId()));
                addDto.setSafetySupName(personnel.getRealName());
            }
            //网格安全员判断
            if (!StringUtils.isEmpty(addDto.getGridSecId())){
                RailLinkappRosterPersonnel personnel = rosterPersonnelMapper.selectById(Long.valueOf(addDto.getGridSecId()));
                addDto.setGridSecName(personnel.getRealName());
            }
            //施工员/领工员
            if (!StringUtils.isEmpty(addDto.getGridForemanId())){
                RailLinkappRosterPersonnel personnel = rosterPersonnelMapper.selectById(Long.valueOf(addDto.getGridForemanId()));
                addDto.setGridForemanName(personnel.getRealName());
            }
            //现场负责人/安全员
            if (!StringUtils.isEmpty(addDto.getGridSitemanId())){
                RailLinkappRosterPersonnel personnel = rosterPersonnelMapper.selectById(Long.valueOf(addDto.getGridSitemanId()));
                addDto.setGridSitemanName(personnel.getRealName());
            }
            //创建时间
            commonService.setCreateAndModifyInfo(addDto);
            addDto.setCreateTime(new Date());
            //number获取
            number_d++;
            addDto.setNumber(number_d);
            addDto.setTenantId(tenantId);
            baseMapper.insert(addDto);
        }
        return errs;
    }

    @Override
    public void edit(RailLinkappGridManagementInfoDTO dto) {
        baseMapper.updateById(dto);
    }

    @Override
    public OrgaStructureChartVO supervisoryOrgaStructureChart() {
         //获取一级项目信息
        //Map<String, String> root = new HashMap<>();
        String tenantId =  linkappUserContextProducer.getNotNullCurrent().getTenantId();
        LinkappTenant linkappTenant = tenantMapper.selectById(tenantId);
        OrgaStructureChartVO rootVo = new OrgaStructureChartVO();
        rootVo.setProjectId(tenantId);
        rootVo.setProjectName(linkappTenant.getPlatformProjectName());
        List<OrgaStructureStaffVO> levelOne = new ArrayList<>();
        //查询 7，9，10
        //安监办主任-默认取花名册-管理人员-项目经理岗位的人员；
        //安监办常务副主任-默认取花名册-管理人员-安全总监岗位的人员；
        //安监办副主任-默认取花名册-管理人员-安全部长岗位的人员；
        SysDictItem sysDictItem_7 = dictItemService.selectByDictItem("jobs", "7");
        SysDictItem sysDictItem_9 = dictItemService.selectByDictItem("jobs", "9");
        SysDictItem sysDictItem_10 = dictItemService.selectByDictItem("jobs", "10");
        RailLinkappRosterPersonnel personnel_7 = railLinkappRosterPersonnelMapper.selectByPostOne(tenantId, "7");
        if (!Objects.isNull(personnel_7)){
            OrgaStructureStaffVO staffVo = new OrgaStructureStaffVO();
            staffVo.setOfficePosition("安监办主任");
            staffVo.setPost(Objects.isNull(sysDictItem_7)?"":sysDictItem_7.getItemText());
            staffVo.setPhoto(personnel_7.getProfilePict());
            staffVo.setRealName(personnel_7.getRealName());
            staffVo.setLinkPhone(personnel_7.getLinkPhone());
            staffVo.setCpId(String.valueOf(personnel_7.getId()));
            levelOne.add(staffVo);
        }
        RailLinkappRosterPersonnel personnel_9 = railLinkappRosterPersonnelMapper.selectByPostOne(tenantId, "9");
        if (!Objects.isNull(personnel_9)){
            OrgaStructureStaffVO staffVo = new OrgaStructureStaffVO();
            staffVo.setOfficePosition("安监办常务副主任");
            staffVo.setPost(Objects.isNull(sysDictItem_9)?"":sysDictItem_9.getItemText());
            staffVo.setPhoto(personnel_9.getProfilePict());
            staffVo.setRealName(personnel_9.getRealName());
            staffVo.setLinkPhone(personnel_9.getLinkPhone());
            staffVo.setCpId(String.valueOf(personnel_9.getId()));
            levelOne.add(staffVo);
        }
        RailLinkappRosterPersonnel personnel_10 = railLinkappRosterPersonnelMapper.selectByPostOne(tenantId, "10");
        if (!Objects.isNull(personnel_10)){
            OrgaStructureStaffVO staffVo = new OrgaStructureStaffVO();
            staffVo.setOfficePosition("安监办副主任");
            staffVo.setPost(Objects.isNull(sysDictItem_10)?"":sysDictItem_10.getItemText());
            staffVo.setPhoto(personnel_10.getProfilePict());
            staffVo.setRealName(personnel_10.getRealName());
            staffVo.setCpId(String.valueOf(personnel_10.getId()));
            staffVo.setLinkPhone(personnel_10.getLinkPhone());
            levelOne.add(staffVo);
        }
        rootVo.setLevelOne(levelOne);
        List<OrgaStructureStaffVO>  levelTwo = new ArrayList<>();
        //获取二级安监专务 和 三级人员信息
        //查询网格
        //用于安监专务去重
        Map<String, List<RailLinkappGridManagementInfoVO>> maps = new HashMap<>();
        RailLinkappGridManagementInfoDTO dto = new RailLinkappGridManagementInfoDTO();
        dto.setTenantId(tenantId);
        List<RailLinkappGridManagementInfoVO> list = baseMapper.getList(dto);
        for (RailLinkappGridManagementInfoVO gridInfo:list){
            List<RailLinkappGridManagementInfoVO> o = maps.get(gridInfo.getSafetySupId());
            if (Objects.isNull(o)){
                OrgaStructureStaffVO staffVO = new OrgaStructureStaffVO();
                staffVO.setOfficePosition("安监专务");
                staffVO.setCpId(gridInfo.getSafetySupId());
                staffVO.setRealName(gridInfo.getSafetySupName());
                staffVO.setPhoto(gridInfo.getSafetySupPict());
                staffVO.setLinkPhone(gridInfo.getSafetySupPhone());
                staffVO.setLevelThree(new ArrayList<>());
                o = new ArrayList<>();
                o.add(gridInfo);
                maps.put(gridInfo.getSafetySupId(),o);
                levelTwo.add(staffVO);
            }else{
                o.add(gridInfo);
                maps.put(gridInfo.getSafetySupId(),o);
            }
        }
        //填充最下级人员信息
        for (OrgaStructureStaffVO vos:levelTwo){
           String cpId =  vos.getCpId();
            List<GridExpVO> expVo =  new ArrayList<>();
                  //  vos.getLevelThree();
            List<RailLinkappGridManagementInfoVO> railLinkappGridManagementInfoVOS = maps.get(cpId);
            if (Objects.isNull(railLinkappGridManagementInfoVOS)){
                continue;
            }
            if (railLinkappGridManagementInfoVOS.size() == 0){
                continue;
            }
            for (RailLinkappGridManagementInfoVO grid:railLinkappGridManagementInfoVOS){
                GridExpVO exp = new GridExpVO();
                exp.setGridAndMileage(grid.getGridName()+grid.getMileageRange());
                List<OrgaStructureStaffVO> arrs_d = new ArrayList<>();
                if (!StringUtils.isEmpty(grid.getGridSecId())){
                    OrgaStructureStaffVO ms =  new OrgaStructureStaffVO();
                    ms.setOfficePosition("网格安全员");
                    ms.setPhoto(grid.getGridSecPict());
                    ms.setRealName(grid.getGridSecName());
                    ms.setLinkPhone(grid.getGridSecPhone());
                    arrs_d.add(ms);
                }
                if (!StringUtils.isEmpty(grid.getGridForemanId())){
                    OrgaStructureStaffVO ms =  new OrgaStructureStaffVO();
                    ms.setOfficePosition("施工员");
                    ms.setPhoto(grid.getGridForemanPict());
                    ms.setRealName(grid.getGridForemanName());
                    ms.setLinkPhone(grid.getGridForemanPhone());
                    arrs_d.add(ms);
                }
                if (!StringUtils.isEmpty(grid.getGridSitemanId())){
                    OrgaStructureStaffVO ms =  new OrgaStructureStaffVO();
                    ms.setOfficePosition("班组负责人");
                    ms.setPhoto(grid.getGridSitemanPict());
                    ms.setRealName(grid.getGridSitemanName());
                    ms.setLinkPhone(grid.getGridSitemanPhone());
                    arrs_d.add(ms);
                }
                if (!StringUtils.isEmpty(grid.getGridMeetId())){
                    OrgaStructureStaffVO ms =  new OrgaStructureStaffVO();
                    ms.setOfficePosition("班组负责人");
                    ms.setPhoto(grid.getGridMeetPict());
                    ms.setRealName(grid.getGridMeetName());
                    ms.setLinkPhone(grid.getGridMeetPhone());
                    arrs_d.add(ms);
                }
                exp.setTens(arrs_d);
                expVo.add(exp);
            }
            vos.setLevelThree(expVo);
        }
        rootVo.setLevelTwo(levelTwo);
        //查询部门信息
        rootVo.setOrgs(railLinkappOrgInfoMapper.selectByTenantIdList(tenantId));
        return rootVo;
    }

    @Override
    public void addMeetAndAnnouncement(List<RailLinkappGridManagementInfoDTO> addList) {
        for (RailLinkappGridManagementInfoDTO dto:addList){
            RailLinkappGridManagementInfo update = new RailLinkappGridManagementInfo();
            update.setId(dto.getId());
            if (StringUtils.isNotEmpty(dto.getGridMeetId())){
                //查询姓名
                RailLinkappRosterPersonnel personnel = rosterPersonnelMapper.selectById(Long.valueOf(dto.getGridMeetId()));
                if (!Objects.isNull(personnel)){
                    update.setGridMeetId(dto.getGridMeetId());
                    update.setGridMeetName(personnel.getRealName());
                }
            }
            if (StringUtils.isNotEmpty(dto.getAnnouncementFileUrl())){
                update.setAnnouncementFileUrl(dto.getAnnouncementFileUrl());
            }
            if (StringUtils.isNotEmpty(update.getAnnouncementFileUrl()) || StringUtils.isNotEmpty(update.getGridMeetId())){
                 baseMapper.updateById(update);
            }
        }
    }
}
